package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class springSecurityUserService implements UserDetailsService {
    //通过网络连接dubbo访问服务端
    @Reference
    private UserService userService;
    @Reference
    private RoleService roleService;
    @Reference
    private PermissionService permissionService;
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户对象
        User user = userService.findByUsername(username);
        if (user == null){
            //对象不存在返回空
            return null;
        }
        //角色权限集合
        List<GrantedAuthority> list = new ArrayList<>();
        //获取用户id
        Integer userId = user.getId();
        //根据用户id查询用户的角色信息
        Set<Role> roles = roleService.findByUserId(userId);
        //遍历roles集合将得到的角色添加到list集合
        if (roles != null){
            for (Role role : roles) {
                list.add(new SimpleGrantedAuthority(role.getKeyword()));
                //获取角色id
                Integer roleId = role.getId();
                //根据角色id查询角色的权限加到list集合
                Set<Permission> permissions = permissionService.findByRoleId(roleId);
                for (Permission permission : permissions) {
                    list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                }
            }
        }
        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
    }
}
